package com.house.twohouse.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.house.common.utils.R;
import com.house.twohouse.entity.vo.FlatsVo;
import com.house.twohouse.entity.vo.QueryVo;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.common.utils.PageUtils;
import com.house.common.utils.Query;

import com.house.twohouse.dao.FlatsDao;
import com.house.twohouse.entity.FlatsEntity;
import com.house.twohouse.service.FlatsService;
import org.springframework.web.servlet.FlashMapManager;


@Service("flatsService")
@SuppressWarnings("all")
public class FlatsServiceImpl extends ServiceImpl<FlatsDao, FlatsEntity> implements FlatsService {



    @Autowired
    private FlatsDao flatsDao;
    @Autowired
    private RestHighLevelClient client;
    //查询新房以及户型 同步到es
    @Override
    public List<FlatsVo> getlist() {
        return flatsDao.getlist();
    }


    /**
     * //根据名字模糊查询
     *     private String name;
     *     //根据地址模糊查询
     *     private String address;
     *     //根据价格区间查询
     *     private BigDecimal xprice;
     *     private BigDecimal dprice;
     *     //根据地区id精确查询
     *     private Integer aid;
     */

    //新房索引名字 house
    @Override
    public R getesList(QueryVo vo) throws IOException {
        SearchRequest searchRequest = new SearchRequest("house");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //根据名字模糊查询
        if (StringUtils.isNotEmpty(vo.getName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("flatsName",vo.getName()));
        }
        //根据地址模糊查询
        if (StringUtils.isNotEmpty(vo.getAddress())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("flatsAddress",vo.getAddress()));
        }
        //根据价格区间查询
        if (vo.getXprice()!=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("flatsAvgPrice").gte(vo.getXprice()));
        }
        if (vo.getDprice()!=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("flatsAvgPrice").lte(vo.getDprice()));
        }
        //根据地区id精确查询
        if (vo.getAid()!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("xianId",vo.getAid()));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        //根据名称高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("flatsName").preTags("<span style='color:red'>").postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //排序 默认为0  1-价格从低到高排序 2-价格从高到低排序   3.开盘时间较早  4.开盘时间较晚
        Integer psort = vo.getPsort();
        if (psort==1){
            searchSourceBuilder.sort("flatsAvgPrice", SortOrder.ASC);
        }else if (psort==2){
            searchSourceBuilder.sort("flatsAvgPrice", SortOrder.DESC);
        }else if (psort==3){
            searchSourceBuilder.sort("starttime",SortOrder.ASC);
        }else if (psort==4){
            searchSourceBuilder.sort("starttime",SortOrder.DESC);
        }
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();

        long numHits = totalHits.value;

        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        SearchHit[] searchHits = hits.getHits();
        ArrayList<FlatsVo> list = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            FlatsVo flatsVo = JSON.parseObject(sourceAsString, new TypeReference<FlatsVo>() {
            });
            //赋值主键
            flatsVo.setFlatsId(Integer.parseInt(id));
            //处理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("flatsName");
            if (highlight!=null){
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                flatsVo.setFlatsName(fragmentString);
            }
            list.add(flatsVo);

        }
        return R.ok().put("eslist",list);
    }

}